package com.haoniu.web.controller.module;

import com.haoniu.common.annotation.Log;
import com.haoniu.common.base.AjaxResult;
import com.haoniu.common.constant.OrderConstants;
import com.haoniu.common.enums.BusinessType;
import com.haoniu.common.enums.RedPacketLogEnum;

import com.haoniu.common.support.Convert;
import com.haoniu.common.utils.huanxin.HuanXinConstants;
import com.haoniu.common.utils.huanxin.HuanXinUtils;
import com.haoniu.framework.util.ShiroUtils;
import com.haoniu.framework.web.page.TableDataInfo;
import com.haoniu.framework.web.service.RedisService;
import com.haoniu.module.domain.database.*;
import com.haoniu.module.service.*;
import com.haoniu.web.controller.tool.CryptoUtils;
import com.haoniu.web.controller.vo.RoomVipVO;
import com.haoniu.web.core.base.BaseController;
import com.haoniu.web.core.config.MoneyDetailTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户 信息操作处理
 *
 * @author admin
 * @date 2019-01-24
 */
@Controller
@RequestMapping("/module/user")
public class UserController extends BaseController {
    private String prefix = "module/user";

    @Autowired
    private UserService userService;
    @Resource
    private UserWalletService userWalletService;
    @Resource
    private UserMoneyDetailService userMoneyDetailService;
    @Resource
    private UserWalletInService userWalletInService;
    @Resource
    private RoomUserService roomUserService;
    @Resource
    private RoomService roomService;
    @Resource
    private RedPacketLogService redPacketLogService;
    @Resource
    private RedisService redisService;
    @Resource
    private UserWalletOutService userWalletOutService;

    @RequiresPermissions("module:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions("module:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User userReq) {
        startPage();
        List<User> list = userService.selectUserList(userReq);
        for (User user : list) {
            UserWallet userWallet = user.getUserWallet();
            if(userWallet!=null){
                BigDecimal money = userWallet.getMoney();
                user.setMoney(money);
                BigDecimal freezeMoney = user.getUserWallet().getFreezeMoney();
                user.setFreezeMoney(freezeMoney);
            }
        }
        return getDataTable(list);
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("module:user:add")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(User user) {
        //给新增用户增加默认密码
        user.setCreateBy(ShiroUtils.getLoginName());
        String salt = CryptoUtils.getSalt();
        user.setSalt(salt);
        String password = redisService.getConfig("kefu.default.password");
        user.setPassword(CryptoUtils.getHash(password, salt));
        if (user.getUserType()!=0&&user.getHeadImg()==null||user.getHeadImg()==""){
            user.setHeadImg("/upload/img/default_avatar.png");
        }
        int result = userService.insertUser(user);

        User existUser = userService.selectUserByPhone(user.getPhone());

        // 生成钱包信息
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(existUser.getId());
        userWallet.setCreateTime(new Date());
        userWalletService.insertUserWallet(userWallet);

        HuanXinUtils.createUser(existUser.getId()+"", HuanXinConstants.HAUNXIN_USER_PASSWORD_DETAULT,user.getNickName());
        return toAjax(result);
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        User user = userService.selectUserById(id);
        mmap.put("user", user);
        return prefix + "/edit";
    }

    /**
     * 用户金额流水
     */
    @RequiresPermissions("module:userDetailMoney:detailList")
    @GetMapping("/detailList/{userId}")
    public String userDetailMoneyList(@PathVariable("userId") Integer userId, ModelMap mmap) {
        mmap.put("userId", userId);
        return "module/userMoneyDetail/userMoneyDetail";
    }


    /**
     * 修改保存用户
     */
    @RequiresPermissions("module:user:edit")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(User user) {
        user.setUpdateBy(ShiroUtils.getLoginName());
        //拼用户头像路径  全路径
        String userImg = user.getHeadImg();
        user.setHeadImg(userImg);
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("module:user:remove")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int result = userService.deleteUserByIds(ids);
        String[] idArray = Convert.toStrArray(ids);
        for (String id:idArray) {
            // 踢出登陆的用户
            User user = userService.selectUserById(Integer.valueOf(id));
            String tokenId = user.getTokenId();
            redisService.del("user_token:"+tokenId);
        }
        return toAjax(result);
    }
    /**
     * 启用用户
     */
    @RequiresPermissions("module:user:recover")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping("/recover")
    @ResponseBody
    public AjaxResult recover(Integer id) {
        return toAjax(userService.recoverUserById(id));
    }

    /**
     * 检查用户
     */
    @PostMapping("/checkUser")
    @ResponseBody
    public AjaxResult check(Integer id) {
        User user = userService.selectUserById(id);
        if (OrderConstants.USER_FORBID.equals(user.getDelFlag())) {
            return error("用户禁用");
        } else if (null == user) {
            return error("用户不存在");
        }
        return success();
    }

    /**
     * 跳转充值界面
     */
    @GetMapping("/toAddMoney")
    public String toEdit(Integer id, ModelMap mmap) {
        //订单id
        mmap.put("userId", id);
        User user = userService.selectUserById(id);
        mmap.put("user",user);
        return prefix + "/addMoney";
    }

    /**
     * 充值
     */
    @RequiresPermissions("module:user:chargeMoney")
    @Log(title = "用户余额充值", businessType = BusinessType.UPDATE)
    @PostMapping("/chargeMoney")
    @ResponseBody
    public AjaxResult chargeMoney(HttpServletRequest request, User user) {
        Integer roleId = getUser().getUserId().intValue();
        if(user.getMoney().intValue() < 0){
            return error("金额不正确");
        }
        UserWallet userWallet = userWalletService.selectUserWalletByUserId(user.getId());

        UserMoneyDetail userMoneyDetail = new UserMoneyDetail();
        userMoneyDetail.setUserId(user.getId());
        userMoneyDetail.setMoney(user.getMoney());
        userMoneyDetail.setAfterMoney(userWallet.getMoney().add(user.getMoney()));
        userMoneyDetail.setType(0);
        userMoneyDetail.setDescription(MoneyDetailTypeEnum.Recharge.desc);
        userMoneyDetail.setObjectType(MoneyDetailTypeEnum.Recharge.type);
        userMoneyDetail.setObjectId(roleId);
        userMoneyDetail.setCreateTime(new Date());
        userMoneyDetailService.insertUserMoneyDetail(userMoneyDetail);

        UserWalletIn userWalletIn = new UserWalletIn();
        userWalletIn.setUserId(user.getId());
        userWalletIn.setMoney(user.getMoney());
        userWalletIn.setStatus(1);
        userWalletIn.setPayType(3);
        userWalletIn.setCreateBy(getUser().getLoginName());
        userWalletIn.setCreateTime(new Date());
        userWalletInService.insertUserWalletIn(userWalletIn);

        userWallet.setMoney(userWallet.getMoney().add(user.getMoney()));
        userWallet.setUpdateTime(new Date());

        return  toAjax(userWalletService.updateUserWallet(userWallet));

    }

    /**
     * 跳转用户余额扣除界面
     */
    @GetMapping("/toReduceMoney")
    public String toReduceMoney(Integer id, ModelMap mmap) {
        //订单id
        mmap.put("userId", id);
        User user = userService.selectUserById(id);
        mmap.put("user",user);
        return prefix + "/reduceMoney";
    }

    /**
     * 扣除余额
     */
    @RequiresPermissions("module:money:reduce")
    @Log(title = "扣除余额", businessType = BusinessType.UPDATE)
    @PostMapping("/reduceMoney")
    @ResponseBody
    public AjaxResult reduceMoney(HttpServletRequest request, User user) {
        Integer roleId = getUser().getUserId().intValue();
        if(user.getMoney().intValue() < 0){
            return error("金额不正确");
        }
        UserWallet userWallet = userWalletService.selectUserWalletByUserId(user.getId());
        BigDecimal money = user.getMoney();
        UserMoneyDetail userMoneyDetail = new UserMoneyDetail();
        userMoneyDetail.setUserId(user.getId());
        userMoneyDetail.setMoney(money);
        userMoneyDetail.setAfterMoney(userWallet.getMoney().add(user.getMoney()));
        userMoneyDetail.setType(1);
        userMoneyDetail.setDescription(MoneyDetailTypeEnum.Reduce.desc);
        userMoneyDetail.setObjectType(MoneyDetailTypeEnum.Reduce.type);
        userMoneyDetail.setObjectId(roleId);
        userMoneyDetail.setCreateTime(new Date());
        userMoneyDetailService.insertUserMoneyDetail(userMoneyDetail);

        money = BigDecimal.ZERO.subtract(money);
        userWallet.setMoney(userWallet.getMoney().add(money));
        userWallet.setUpdateTime(new Date());

        return  toAjax(userWalletService.updateUserWallet(userWallet));
    }

    /**
     * 房间踢出会员
     */
    @RequiresPermissions("module:user:removeVip")
    @Log(title = "房间踢出会员", businessType = BusinessType.UPDATE)
    @PostMapping("/removeVip")
    @ResponseBody
    public AjaxResult removeVip(RoomVipVO roomVipVO) {
        RoomUser roomUser = roomUserService.getUser(roomVipVO.getId(), roomVipVO.getRoomId());
        if(null == roomUser){
            return error("用户不存在");
        }
        roomUserService.deleteRoomUserById(roomUser.getId());

        Room room = roomService.selectRoomById(roomUser.getRoomId());

        HuanXinUtils.deleteUserFromGroup(roomUser.getUserId().toString(),room.getHuanxinGroupId());

        return toAjax(1);
    }

    /**
     *  红包记录统计
     * @param userId
     * @param mmap
     * @return
     */
    @RequiresPermissions("module:user:redCount")
    @GetMapping("/redCount/{userId}")
    public String detail(@PathVariable("userId") Integer userId, ModelMap mmap)
    {
        // 发红包
       BigDecimal sendPacketMoney =  redPacketLogService.countRedMoneyByType(RedPacketLogEnum.SendRedPacketMine.type,userId);
        // 领取红包
        BigDecimal robPacketMoney =  redPacketLogService.countRedMoneyByType(RedPacketLogEnum.RobRedPacketMine.type,userId);
        // 踩雷
        BigDecimal outPunishMoney =   redPacketLogService.countRedMoneyByType(RedPacketLogEnum.OutPunishMoney.type,userId);
        // 收到雷包
        BigDecimal getPunishMoney =   redPacketLogService.countRedMoneyByType(RedPacketLogEnum.GetPunishMoney.type,userId);
        // 福利包
        BigDecimal welfareMoney =  redPacketLogService.countRedMoneyByType(RedPacketLogEnum.WELFARE.type,userId);
        // (雷)福利包
        BigDecimal welfareThunderMoney =  redPacketLogService.countRedMoneyByType(RedPacketLogEnum.WelfareThunder.type,userId);
        //充值总额
        BigDecimal userWalletInTotalMoney = userWalletInService.selectUserWalletInMoney(userId);
        //提现总额
        BigDecimal userWalletOutTotalMoney = userWalletOutService.selectUserWalletOutMoney(userId);
        // 盈亏:
        Map map = new LinkedHashMap<>(16);
        map.put("发红包：",sendPacketMoney);
        map.put("领取红包：",robPacketMoney);
        map.put("踩雷：",outPunishMoney);
        map.put("收到雷包：",getPunishMoney);
        map.put("福利包：",welfareMoney);
        map.put("(雷)福利包：",welfareThunderMoney);
        BigDecimal earnMoney =  sendPacketMoney.add(getPunishMoney).add(welfareMoney).add(welfareThunderMoney).add(outPunishMoney).add(robPacketMoney);
        map.put("盈亏：",earnMoney);
        map.put("充值总额",userWalletInTotalMoney);
        map.put("提现总额",userWalletOutTotalMoney);
        mmap.addAttribute("totalMap",map);
        return prefix + "/redDetail";
    }

    /**
     *  重置支付密码
     */
    @RequiresPermissions("module:user:resetPayPwd")
    @Log(title = "重置支付密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPayPwd")
    @ResponseBody
    public AjaxResult resetPayPwd(Integer userId) {
        return toAjax(userWalletService.resetPayPwd(userId));
    }



}
